<script lang="ts" setup>
import { ref, onMounted, h } from 'vue';
import { Card, Form, Input, Button, Switch, Table, Tag, Space, Alert, Modal } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';

interface LoginRecord {
  id: string;
  ip: string;
  location: string;
  device: string;
  browser: string;
  loginTime: string;
  status: 'success' | 'failed';
}

const loading = ref(false);
const passwordForm = ref();
const securitySettings = ref({
  twoFactorAuth: false,
  loginNotification: true,
  ipWhitelist: false,
  sessionTimeout: 30,
});

const passwordData = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
});

const loginRecords = ref<LoginRecord[]>([]);

const loginColumns: TableColumnsType<LoginRecord> = [
  {
    title: 'IP地址',
    dataIndex: 'ip',
    key: 'ip',
    width: 150,
  },
  {
    title: '登录地点',
    dataIndex: 'location',
    key: 'location',
    width: 150,
  },
  {
    title: '设备信息',
    key: 'device',
    width: 200,
    customRender: ({ record }) => {
      return h('div', [
        h('div', record.device),
        h('div', { class: 'text-gray-500 text-sm' }, record.browser)
      ]);
    },
  },
  {
    title: '登录时间',
    dataIndex: 'loginTime',
    key: 'loginTime',
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }) => {
      const statusMap = {
        success: { color: 'success', text: '成功' },
        failed: { color: 'error', text: '失败' },
      };
      const status = statusMap[record.status];
      return h(Tag, { color: status.color }, () => status.text);
    },
  },
];

const handlePasswordChange = async (values: any) => {
  loading.value = true;
  try {
    // TODO: 调用API修改密码
    // await api.changePassword(values);
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    Modal.success({
      title: '密码修改成功',
      content: '您的密码已成功修改，请使用新密码登录。',
    });
    
    // 重置表单
    passwordForm.value?.resetFields();
  } catch (error) {
    console.error('修改密码失败:', error);
    Modal.error({
      title: '修改失败',
      content: '密码修改失败，请稍后重试。',
    });
  } finally {
    loading.value = false;
  }
};

const handleSecuritySettingChange = async (key: string, value: any) => {
  try {
    // TODO: 调用API更新安全设置
    // await api.updateSecuritySetting({ [key]: value });
    
    console.log(`更新安全设置: ${key} = ${value}`);
  } catch (error) {
    console.error('更新安全设置失败:', error);
    // 回滚设置
    (securitySettings.value as any)[key] = !value;
  }
};

const fetchLoginRecords = async () => {
  loading.value = true;
  try {
    // TODO: 调用API获取登录记录
    // const response = await api.getLoginRecords();
    // loginRecords.value = response.data;
    
    // 模拟数据
    loginRecords.value = [
      {
        id: '1',
        ip: '192.168.1.100',
        location: '北京市',
        device: 'MacBook Pro',
        browser: 'Chrome 120.0',
        loginTime: '2024-01-15 09:30:00',
        status: 'success',
      },
      {
        id: '2',
        ip: '10.0.0.50',
        location: '上海市',
        device: 'iPhone 15',
        browser: 'Safari 17.0',
        loginTime: '2024-01-14 18:45:00',
        status: 'success',
      },
      {
        id: '3',
        ip: '203.0.113.1',
        location: '未知',
        device: 'Windows PC',
        browser: 'Edge 120.0',
        loginTime: '2024-01-14 02:15:00',
        status: 'failed',
      },
    ];
  } catch (error) {
    console.error('获取登录记录失败:', error);
  } finally {
    loading.value = false;
  }
};

const validatePassword = (_rule: any, value: string) => {
  if (value && value !== passwordData.value.newPassword) {
    return Promise.reject('两次输入的密码不一致');
  }
  return Promise.resolve();
};

onMounted(() => {
  fetchLoginRecords();
});
</script>

<template>
  <div class="p-5">
    <!-- 安全提醒 -->
    <Alert
      message="安全提醒"
      description="为了您的账户安全，建议定期修改密码并开启双因子认证。"
      type="info"
      show-icon
      class="mb-6"
    />
    
    <!-- 密码修改 -->
    <Card title="密码修改" :bordered="false" class="mb-6">
      <template #extra>
        <span class="text-blue-500">🔒</span>
      </template>
      
      <Form
        ref="passwordForm"
        :model="passwordData"
        layout="vertical"
        @finish="handlePasswordChange"
        class="max-w-md"
      >
        <Form.Item
          label="当前密码"
          name="currentPassword"
          :rules="[
            { required: true, message: '请输入当前密码' },
            { min: 6, message: '密码长度至少6位' }
          ]"
        >
          <Input.Password
            v-model:value="passwordData.currentPassword"
            placeholder="请输入当前密码"
          />
        </Form.Item>
        
        <Form.Item
          label="新密码"
          name="newPassword"
          :rules="[
            { required: true, message: '请输入新密码' },
            { min: 8, message: '新密码长度至少8位' },
            { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: '密码必须包含大小写字母和数字' }
          ]"
        >
          <Input.Password
            v-model:value="passwordData.newPassword"
            placeholder="请输入新密码"
          />
        </Form.Item>
        
        <Form.Item
          label="确认密码"
          name="confirmPassword"
          :rules="[
            { required: true, message: '请确认新密码' },
            { validator: validatePassword }
          ]"
        >
          <Input.Password
            v-model:value="passwordData.confirmPassword"
            placeholder="请再次输入新密码"
          />
        </Form.Item>
        
        <Form.Item>
          <Button type="primary" html-type="submit" :loading="loading">
            修改密码
          </Button>
        </Form.Item>
      </Form>
    </Card>
    
    <!-- 安全设置 -->
    <Card title="安全设置" :bordered="false" class="mb-6">
      <template #extra>
        <span class="text-green-500">🛡️</span>
      </template>
      
      <div class="space-y-4">
        <div class="flex justify-between items-center py-3 border-b">
          <div>
            <div class="font-medium">双因子认证</div>
            <div class="text-gray-500 text-sm">使用手机验证码进行二次验证</div>
          </div>
          <Switch
            v-model:checked="securitySettings.twoFactorAuth"
            @change="(value) => handleSecuritySettingChange('twoFactorAuth', value)"
          />
        </div>
        
        <div class="flex justify-between items-center py-3 border-b">
          <div>
            <div class="font-medium">登录通知</div>
            <div class="text-gray-500 text-sm">新设备登录时发送通知</div>
          </div>
          <Switch
            v-model:checked="securitySettings.loginNotification"
            @change="(value) => handleSecuritySettingChange('loginNotification', value)"
          />
        </div>
        
        <div class="flex justify-between items-center py-3 border-b">
          <div>
            <div class="font-medium">IP白名单</div>
            <div class="text-gray-500 text-sm">仅允许白名单IP登录</div>
          </div>
          <Switch
            v-model:checked="securitySettings.ipWhitelist"
            @change="(value) => handleSecuritySettingChange('ipWhitelist', value)"
          />
        </div>
        
        <div class="py-3">
          <div class="font-medium mb-2">会话超时</div>
          <div class="text-gray-500 text-sm mb-3">设置自动登出时间（分钟）</div>
          <Input
            v-model:value="securitySettings.sessionTimeout"
            type="number"
            :min="5"
            :max="480"
            suffix="分钟"
            style="width: 120px"
          />
        </div>
      </div>
    </Card>
    
    <!-- 登录记录 -->
    <Card title="登录记录" class="mt-6">
      <template #extra>
        <span class="text-purple-500">📱</span>
      </template>
      
      <Table
        :columns="loginColumns"
        :data-source="loginRecords"
        :loading="loading"
        :pagination="{
          total: loginRecords.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }"
        row-key="id"
      />
    </Card>
  </div>
</template>

<style scoped>
.ant-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.ant-alert {
  border-radius: 8px;
}

.ant-form-item-label > label {
  font-weight: 500;
}

.ant-switch {
  background-color: #f0f0f0;
}

.ant-switch-checked {
  background-color: #1890ff;
}

.ant-table-thead > tr > th {
  background-color: #fafafa;
  font-weight: 600;
}

.ant-tag {
  border-radius: 4px;
  font-weight: 500;
}
</style>